package com.cy.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cy.common.entity.Result;
import com.cy.common.exception.CommonException;
import com.cy.common.utils.JwtUtils;
import com.cy.pojo.Academy;
import com.cy.pojo.Department;
import com.cy.pojo.User;
import com.cy.pojo.vo.AcademyVo;
import com.cy.pojo.vo.AcademyTreeVo;
import com.cy.pojo.vo.SearchVo;
import com.cy.service.AcademyService;
import com.cy.service.DepartmentService;
import com.cy.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author 残影
 * @description 学院信息
 * @date 2022-04-19
 */
@RestController
@RequestMapping("/academy")
@Api(tags = "学院信息模块")
public class AcademyController {
    @Autowired
    private AcademyService academyService;
    @Autowired
    private UserService userService;
    @Autowired
    private DepartmentService departmentService;

    /**
     * 根据ID查询学院信息
     */
    @GetMapping("{id}")
    @ApiOperation("根据ID查询学院信息")
    public Result findById(@PathVariable Integer id) {
        Academy academy = academyService.getById(id);
        if (academy != null) {
            return Result.ok("查询学院信息成功", academy);
        } else {
            return Result.failed(201, "没有该学院信息");
        }
    }

    /**
     * 分页查询学院信息
     */
    @ApiOperation("分页查询学院信息")
    @GetMapping("/list")
    public Result list(SearchVo searchVo) {
        //分页构造器
        Page<Academy> buildPage = new Page<>(searchVo.getPage(), searchVo.getLimit());
        //条件构造器
        QueryWrapper<Academy> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(searchVo.getName())) {
            queryWrapper.like("academy_name", searchVo.getName());
        }
        IPage<Academy> pageList = academyService.page(buildPage, queryWrapper);
        return Result.ok("查询成功", pageList.getRecords()).put("total", pageList.getTotal());
    }

    /**
     * 查询所有学院信息
     */
    @ApiOperation("查询所有学院信息")
    @GetMapping("/listAll")
    public Result listAll() {
        return Result.ok("查询成功", academyService.list());
    }

    /**
     * 查询所有学院包括系
     */
    @ApiOperation("查询所有学院包括系")
    @GetMapping("/listAllTree")
    public Result listAllTree() {
        List<AcademyTreeVo> academyTreeVoArrayList = new ArrayList<>();
        List<Department> departmentList = departmentService.list();
        List<Academy> academyList = academyService.list();
        academyList.forEach(academy -> {
            List<Department> departmentList1 = new ArrayList<>();
            AcademyTreeVo departmentTreeVo = new AcademyTreeVo();
            BeanUtils.copyProperties(academy, departmentTreeVo);
            departmentList.forEach(department -> {
                if (department.getAcademyId() == academy.getAcademyId()) {
                    departmentList1.add(department);
                }
            });
            departmentTreeVo.setDepartmentList(departmentList1);
            academyTreeVoArrayList.add(departmentTreeVo);
        });
        return Result.ok("查询成功", academyTreeVoArrayList);
    }

    /**
     * 保存学院信息
     */
    @PostMapping
    @ApiOperation("保存学院信息")
    public Result save(@RequestBody AcademyVo academyVo, HttpServletRequest request) {
        Long currentUserId = JwtUtils.getUserIdByRequest(request);
        User currentUser = userService.getById(currentUserId);

        Academy academy = new Academy();
        BeanUtils.copyProperties(academyVo, academy);

        academy.setCreateTime(new Date());
        academy.setUpdateTime(new Date());
        academy.setCreateBy(currentUser.getNickName());
        academy.setUpdateBy(currentUser.getNickName());

        boolean b = academyService.save(academy);
        if (b) {
            return Result.ok("保存用户学院信息成功", academy);
        } else {
            return Result.failed("保存学院信息失败");
        }
    }

    /**
     * 修改学院信息
     */
    @PutMapping("{id}")
    @ApiOperation("修改学院信息")
    public Result update(@RequestBody AcademyVo academyVo, @PathVariable Long id, HttpServletRequest request) {
        Long currentUserId = JwtUtils.getUserIdByRequest(request);
        User currentUser = userService.getById(currentUserId);

        Academy academy = academyService.getById(id);
        if (ObjectUtils.isEmpty(academy)) {
            throw new CommonException("学院不存在");
        }
        BeanUtils.copyProperties(academyVo, academy);
        academy.setUpdateTime(new Date());
        academy.setUpdateBy(currentUser.getNickName());

        boolean b = academyService.saveOrUpdate(academy);
        if (b) {
            return Result.ok("修改学院信息成功", academy);
        } else {
            return Result.failed("修改学院信息失败");
        }
    }

    /**
     * 删除学院信息
     */
    @DeleteMapping("{id}")
    @ApiOperation("删除学院信息")
    public Result delete(@PathVariable Long id) {
        QueryWrapper<Department> wrapper = new QueryWrapper<>();
        wrapper.eq("academy_id", id);
        List<Department> list = departmentService.list(wrapper);
        if (list.size() > 0) {
            throw new CommonException("请先删除学院的的系");
        }
        boolean b = academyService.removeById(id);
        if (b) {
            return Result.ok("删除学院信息成功");
        } else {
            return Result.failed("删除学院信息失败");
        }
    }
}
